using Microsoft.AspNetCore.Mvc;
using JTZY.Model.Goods.Dto;
using JTZY.Model.Goods;
using JTZY.Service.Goods.IGoodsService;
using JTZY.Admin.WebApi.Filters;
using JTZY.Service.Goods;
using JTZY.Model.Product.Dto;
using JTZY.Service.Product.IProductService;
using JTZY.Service.Business.IBusinessService;
using JTZY.Service.Brand.IBrandService;
using JTZY.Service.Product;
using JTZY.Model.Business;
using JTZY.Model.Product;

//创建时间：2024-10-31
namespace JTZY.Admin.WebApi.Controllers.Goods
{
    /// <summary>
    /// 商品表
    /// </summary>
    [Verify]
    [Route("goods/Corecmsgoods")]
    public class CorecmsgoodsController : BaseController
    {
        /// <summary>
        /// 商品表接口
        /// </summary>
        private readonly ICorecmsgoodsService _CorecmsgoodsService;
        private readonly IProdinfoService _ProdinfoService;
        private readonly ICorecmsuserstockService _usService;
        private readonly ICorecmsuserService _userService;
        private readonly IStockFlowItemService _stockFlowItemService;
        private readonly ICorecmsproductsService _corecmsproductsService;
        private readonly ICorecmsbrandService _corecmsbrandService;

        public CorecmsgoodsController(ICorecmsgoodsService CorecmsgoodsService,
            ICorecmsuserService userService, IStockFlowItemService stockFlowItemService,
            ICorecmsproductsService corecmsproductsService, ICorecmsbrandService corecmsbrandService,
            ICorecmsuserstockService usService, IProdinfoService prodinfoService)
        {
            _CorecmsgoodsService = CorecmsgoodsService;
            _ProdinfoService = prodinfoService;
            _usService = usService;
            _userService = userService;
            _stockFlowItemService = stockFlowItemService;
            _corecmsproductsService = corecmsproductsService;
            _corecmsbrandService = corecmsbrandService;
        }

        /// <summary>
        /// 查询商品表列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("list")]
        [ActionPermissionFilter(Permission = "corecmsgoods:list")]
        public IActionResult QueryCorecmsgoods([FromQuery] CorecmsgoodsQueryDto parm)
        {
            var response = _CorecmsgoodsService.GetList(parm);
            return SUCCESS(response);
        }

        /// <summary>
        /// 查询商品分类列表树
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("treeList")]
        [ActionPermissionFilter(Permission = "corecmsgoodscategory:list")]
        public IActionResult QueryTreeCorecmsgoodscategory()
        {
            var response = _CorecmsgoodsService.GetTreeList();
            return SUCCESS(response);
        }

        /// <summary>
        /// 查询商品表详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet("{Id}")]
        [ActionPermissionFilter(Permission = "corecmsgoods:query")]
        public IActionResult GetCorecmsgoods(int Id)
        {
            var response = _CorecmsgoodsService.GetInfo(Id);

            var info = response.Adapt<CorecmsgoodsDto>();
            return SUCCESS(info);
        }

        /// <summary>
        /// 导出商品表
        /// </summary>
        /// <returns></returns>
        [Log(Title = "商品表", BusinessType = BusinessType.EXPORT, IsSaveResponseData = false)]
        [HttpGet("export")]
        [ActionPermissionFilter(Permission = "corecmsgoods:export")]
        public IActionResult Export([FromQuery] CorecmsgoodsQueryDto parm)
        {
            parm.PageNum = 1;
            parm.PageSize = 100000;
            var list = _CorecmsgoodsService.ExportList(parm).Result;
            if (list == null || list.Count <= 0)
            {
                return ToResponse(ResultCode.FAIL, "没有要导出的数据");
            }
            var result = ExportExcelMini(list, "商品表", "商品表");
            return ExportExcel(result.Item2, result.Item1);
        }


        [HttpPost("track")]
        [ActionPermissionFilter(Permission = "corecmsgoods:query")]
        public IActionResult track([FromBody] ProdQueryDto param)
        {
            var no = "";
            var f = "";
            if (string.IsNullOrEmpty(param.snCode))
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "未检测到物码");

            }
            bool isScan = false;
            if (param.snCode.Contains("http"))
            {
                var Querys = UrlStringHelper.GetQueryDictionary(param.snCode);
                if (Querys.Keys.Contains("no"))
                    no = Querys["no"];
                if (Querys.Keys.Contains("n"))
                    no = Querys["n"];
                if (Querys.Keys.Contains("f"))
                    f = Querys["f"];
                if (string.IsNullOrEmpty(f))
                {
                    f = "n";
                }
                isScan = true;
            }
            else
            {
                //f = "n";
                no = param.snCode;
            }
            var userId = HttpContext.GetUId();
            Prodinfo response = null;
            if (isScan)
            {
                response = f == "w" ? _ProdinfoService.GetProdinfoByCode(no,f) : _ProdinfoService.GetProdinfoByNCode(no);
            }
            else
            {
                response = _ProdinfoService.GetProdinfoByCode(no, "w");
                if(response==null)
                    response = _ProdinfoService.GetProdinfoByCode(no, "n");
            }
            if (response == null)
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "未检测到物码");
            }

            string userName = string.Empty;
            if (response.UserId.HasValue && response.UserId.Value > 0 && response.UserId != userId)
            {
                var cus = _userService.GetById(response.UserId);
                if (cus == null || cus.ParentId != userId)
                {
                    userName= cus.UserName;
                    return ToResponse(ResultCode.CUSTOM_ERROR, "未检测到物码");
                }
            }

            if (response.UserCusId.HasValue&& response.UserCusId>0)
            {
                var cus = _userService.GetById(response.UserCusId);
                if (cus == null || cus.ParentId != userId)
                {
                    return ToResponse(ResultCode.CUSTOM_ERROR, "未检测到物码");
                }
            }

            var info = response.Adapt<ProdinfoDto>();
            var prod = _usService.Queryable().Where(us => us.UserId == userId && us.ProductId == response.ProductId).First();
            if (prod != null)
            {
                info.SkuImage = prod.SkuImage;
                info.SkuName = prod.SkuName;
                info.Price = response.CostPrice ?? 0;
                //info.UserName = userName;
            }
            var item=_corecmsproductsService.GetById(response.ProductId);
            if (item != null)
            {
                info.BarCode = item.Barcode;
                var goods=_CorecmsgoodsService.GetById(item.GoodsId);
                if (goods != null) 
                {
                   var brand= _corecmsbrandService.GetById(goods.BrandId);
                    if (brand != null) 
                    {
                        info.BrandName = brand.Name;
                    }
                }
            }



            var list=_stockFlowItemService.Queryable().LeftJoin<Corecmsuser>((it,user)=>it.UserId==user.Id)
                .Where((it, user) => it.SnCode == response.SnCode && (it.UserId == userId || user.ParentId == userId))
                .Select((it,user)=>new StockFlowItem
                {
                    SheetNo=it.SheetNo,
                    CreateTime=it.CreateTime,
                    SnCode=it.SnCode,
                    UserId=it.UserId,
                    Price=it.Price,
                    DbNo=it.DbNo,
                    OrderType=it.OrderType,
                    Memo=it.Memo,
                    UserName=user.UserName,
                })
                .OrderByDescending(it=>it.CreateTime).ToList();
            info.stockFlowItems = list;

            return SUCCESS(info);
        }
    }
}